package com.blog.controller.backend;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.blog.entity.AdminUser;
import com.blog.service.AdminUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author mars123
 * @since 2019-07-02
 */
@Controller("backendAdminUser")
@RequestMapping("/backend/adminUser")
public class AdminUserController {


    @Autowired
    public AdminUserService adminUserService;

    @RequestMapping("/login")
    public String login(String username, String password, HttpSession session, HttpServletRequest request) {
        if (request.getMethod().equals("POST") && adminUserService.login(username, password, session)) {
            return "redirect:/backend/index";
        }
        return "backend/admin/login";
    }

    @RequestMapping("/logout")
    public String logout(HttpSession session) {
        session.invalidate();
        return "redirect:/backend/adminUser/login";
    }

    @RequestMapping("/index")
    public String index(Model model, Integer curPage) {

        model.addAttribute("page", adminUserService.index(null, new Page<AdminUser>(curPage == null ? 1 : curPage, 5)));
        return "backend/admin/index";
    }

    @RequestMapping("/create")
    public String create(@ModelAttribute("adminUser") AdminUser adminUser, HttpServletRequest request) {
        if (request.getMethod().equals("POST") && adminUserService.create(adminUser) != null) {
            return "redirect:/backend/adminUser/view?id=" + adminUser.getId();
        }
        return "backend/admin/create";
    }

    @RequestMapping("/update")
    public String update(@ModelAttribute("adminUser") AdminUser adminUser, Integer id, HttpServletRequest request, Model model) {
        if (request.getMethod().equals("POST") && adminUserService.update(adminUser) != null) {
            return "redirect:/backend/adminUser/view?id=" + adminUser.getId();
        }
        model.addAttribute("adminUser", adminUser.selectOne(new EntityWrapper<AdminUser>().eq("id", id)));
        return "backend/admin/update";
    }

    @RequestMapping("/view")
    public String view(Integer id, Model model) {
        model.addAttribute("adminUser", adminUserService.view(id));
        return "backend/admin/view";
    }

    @RequestMapping("/delete")
    public String delete(Integer id) {
        System.out.println(id);
        adminUserService.delete(id);
        return "redirect:/backend/adminUser/index";
    }

}

